package com.bingo.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.bingo.demo.pojo.Comment;
import com.bingo.demo.pojo.Essay;
import com.bingo.demo.pojo.User;
import com.bingo.demo.service.CommentService;
import com.bingo.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;

    @RequestMapping("addComment.action")
    @ResponseBody
    public JSONObject addComment(HttpServletRequest request, HttpSession session){
        JSONObject json = new JSONObject();
        String content = request.getParameter("comment");
        String userId = request.getParameter("userId");
        String essayId = request.getParameter("essayId");
        if(userId == null){
            json.put("msg","请您先登录");
            return json;
        }
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setUserId(Integer.parseInt(userId));
        comment.setEssayId(Integer.parseInt(essayId));
        //根据id找到名字
        User user = userService.findUserById(comment.getUserId());
        comment.setUsername(user.getName());
        commentService.addComment(comment);
        //将新评论添加到session中去
        List<Comment> allList = (List<Comment>) session.getAttribute("commentList");
        allList.add(comment);
        session.setAttribute("commentList",allList);
        json.put("code",0);
        json.put("msg","评论成功,刷新页面生效");
        return json;
    }

    @RequestMapping("deleteComment.action")
    @ResponseBody
    public JSONObject deleteComment(HttpServletRequest request,HttpSession session){
        JSONObject json = new JSONObject();
        String commentId = request.getParameter("commentId");
        List<Comment> allList = (List<Comment>) session.getAttribute("commentList");
        Comment comment = commentService.findById(Integer.parseInt(commentId));
        allList.remove(comment);
        session.setAttribute("commentList",allList);
        if(!commentId.equals("")){
            Integer id = Integer.parseInt(commentId);
            commentService.deleteById(id);
            json.put("code",0);
            json.put("msg","删除成功,刷新页面生效");
        }else {
            json.put("code",1);
            json.put("msg","评论已删除");
        }
        return json;
    }
}
